package com.ynkbny.service.impl;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynkbny.base.PageResult;
import com.ynkbny.domain.DeviceMapper;
import com.ynkbny.domain.Enterprise;
import com.ynkbny.domain.User;
import com.ynkbny.domain.dto.EnterpriseDTO;
import com.ynkbny.domain.dto.TEpUploadTimeDTO;
import com.ynkbny.domain.pojo.EnterpriseGetNameVO;
import com.ynkbny.domain.pojo.EnterprisePaginReqVO;
import com.ynkbny.lgapi.YnBk;
import com.ynkbny.mapper.DevicePointMapper;
import com.ynkbny.mapper.EnterpriseMapper;
import com.ynkbny.mapper.UserMapper;
import com.ynkbny.service.EnterpriseService;
import com.ynkbny.service.TEpUploadTimeService;
import com.ynkbny.service.TokenService;
import com.ynkbny.service.outsideinterface.MyClient;
import com.ynkbny.util.BusinessException;
import com.ynkbny.util.Res;
import com.ynkbny.util.SearchUtil;
import com.ynkbny.util.UserRoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业基本信息表-表服务实现类
 *
 * @author : juzipi123
 * @date : 2023-7-5
 */
@Slf4j
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Resource
    private TokenService tokenService;

    @Resource
    private YnBk ynBk;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Value("${measurement.host}")
    private String host;

    @Value("${measurement.rwk}")
    private String rwk;

    @Value("${measurement.apply}")
    private String apply;

    @Value("${measurement.update}")
    private String update;

    @Value("${measurement.requestAK}")
    private String requestAk;

    @Resource
    private MyClient client;

    @Resource
    private TEpUploadTimeService uploadTimeService;

    @Resource
    private UserRoleUtil<Enterprise> userRoleUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private DevicePointMapper devicePointMapper;

    /**
     * 分页查询
     *
     * @author : juzipi123
     * @param vo 筛选条件
     * @return 查询结果
     */
    @Override
    public PageResult<Enterprise> paginQuery(EnterprisePaginReqVO vo) {
        log.info("入参：{}",vo);

        //1. 构建动态查询条件
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(vo.getCmpName())) {
            queryWrapper.like("cmp_name", vo.getCmpName());
        }
        if (ObjectUtils.isNotEmpty(vo.getEnterpriseCode())) {
            queryWrapper.eq("enterprise_code", vo.getEnterpriseCode());
        }
        if (ObjectUtils.isNotEmpty(vo.getIsorg())) {
            queryWrapper.eq("isorg", vo.getIsorg());
        }

        if (ObjectUtils.isNotEmpty(vo.getCorporationName())) {
            queryWrapper.like("corporation_name", vo.getCorporationName());
        }

        //注册日期
        if (ObjectUtils.isNotEmpty(vo.getStartDate())) {
            queryWrapper.le("start_date", vo.getStartDate());
        }
        if (ObjectUtils.isNotEmpty(vo.getEndDate())) {
            queryWrapper.ge("end_date", vo.getEndDate());
        }

        if (ObjectUtils.isNotEmpty(vo.getTypeCode())) {
            queryWrapper.eq("type_code", vo.getTypeCode());
        }

        if (ObjectUtils.isNotEmpty(vo.getEnergyConsumeLevel())) {
            queryWrapper.eq("energy_consume_level", vo.getEnergyConsumeLevel());
        }
        if (ObjectUtils.isNotEmpty(vo.getPhone())) {
            queryWrapper.eq("phone", vo.getPhone());
        }

        if (ObjectUtils.isNotEmpty(vo.getProductionLine())) {
            queryWrapper.eq("production_line", vo.getProductionLine());
        }
        if (ObjectUtils.isNotEmpty(vo.getLeadingProduct())) {
            queryWrapper.eq("leading_product", vo.getLeadingProduct());
        }
        if (ObjectUtils.isNotEmpty(vo.getGroupName())) {
            queryWrapper.eq("group_name", vo.getGroupName());
        }
        if (ObjectUtils.isNotEmpty(vo.getGroupAddress())) {
            queryWrapper.eq("group_address", vo.getGroupAddress());
        }
        if (ObjectUtils.isNotEmpty(vo.getOrgType())) {
            queryWrapper.eq("org_type", vo.getOrgType());
        }

        queryWrapper.eq("del_flag", 0);

        queryWrapper.orderByDesc("register_date");

        Page<Enterprise> page = new Page<>(vo.getCurrentPage(), vo.getPageSize());

        //2. 返回结果
//        PageResult<Enterprise> enterprisePageResult = new PageResult<>(this.page(page, queryWrapper));
        Page<Enterprise> pageList = userRoleUtil.getPageList(page, queryWrapper, this.baseMapper);
        return new PageResult<>(pageList);
    }

    /**
     * 新增数据
     *
     * @author : juzipi123
     * @param enterpriseDTO 实例对象
     * @return 是否成功
     */
    @Override
    public Boolean save(EnterpriseDTO enterpriseDTO) {
        log.info("入参：{}",enterpriseDTO);

        //统一社会信用代码
        String enterpriseCode = enterpriseDTO.getEnterpriseCode();

        //1. 构建动态查询条件
        LambdaQueryWrapper<Enterprise> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Enterprise::getEnterpriseCode, enterpriseCode);
        queryWrapper.eq(Enterprise::getDelFlag, 0);
        List<Enterprise> enterpriseList = this.list(queryWrapper);
        if (ObjectUtils.isNotEmpty(enterpriseList)) {
            log.error("统一社会信用代码 不可重复添加");
            throw new BusinessException(500, "统一社会信用代码 已存在，不可重复添加");
        }
        enterpriseDTO.setDelFlag("0");

        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseDTO, enterprise);

        boolean save = this.save(enterprise);
        log.info("方法返回：{}",save);
        return save;
    }

    /**
     * 通过ID查询单条数据
     *
     * @author : juzipi123
     * @param enterpriseId 主键
     * @return 实例对象
     */
    @Override
    public Enterprise queryById(String enterpriseId) {
        log.info("入参：{}",enterpriseId);
        Enterprise byId = this.getById(enterpriseId);
        log.info("方法返回：{}",byId);
        return byId;
    }

    /**
     * 通过主键进行逻辑删除数据
     *
     * @author : juzipi123
     * @param enterpriseId 主键
     * @return 是否成功
     */
    @Override
    public Boolean logicRemoveById(String enterpriseId) {
        log.info("入参：{}",enterpriseId);
        LambdaUpdateChainWrapper<Enterprise> updateChainWrapper = new LambdaUpdateChainWrapper<>(this.getBaseMapper());
        updateChainWrapper.set(Enterprise::getDelFlag, 1);
        updateChainWrapper.eq(Enterprise::getEnterpriseId, enterpriseId);
        updateChainWrapper.eq(Enterprise::getDelFlag, 0);
        boolean update = updateChainWrapper.update();
        log.info("方法返回：{}",update);
        return update;
    }

    /**
     * 根据图片路径删除指定位置图片
     *
     * @param imagePath
     * @return
     */
    public static boolean deleteImage(String imagePath) {
        // 创建File对象
        File imageFile = new File(imagePath);
        // 检查文件是否存在
        if (!imageFile.exists()) {
            return false;
        }
        // 尝试删除文件
        boolean isDeleted = imageFile.delete();
        return isDeleted;
    }

    /**
     * 批量逻辑删除
     *
     * @param ids
     * @return
     */
    @Override
    public Boolean logicRemoveBatchById(List<Long> ids) {
        this.removeBatchByIds(ids);
        return null;
    }

    /**
     * 获取工作密钥
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @return 获取结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean getSecretKey(String enterpriseId) {
        log.info("入参：{}",enterpriseId);

        //根据主键以及未删除，查询出该条数据
        Enterprise enterprise = this.queryById(enterpriseId);
        log.info("查询出该条数据:{}",enterprise);

        //构建 获取工作密钥 需要的参数 1.统一社会信用代码 enterpriseCode 2. 原工作密钥（首次申请工作密钥，则无需此字段）secretKey
        HashMap<String, String> map = new HashMap<>(8);

        //统一社会信用代码 enterpriseCode
        map.put("enterpriseCode", enterprise.getEnterpriseCode());

        //原工作密钥（首次申请工作密钥，则无需此字段）secretKey
        String secretKey = enterprise.getSecretKey();
        if (ObjectUtils.isNotEmpty(secretKey)) {
            map.put("secretKey", secretKey);
        }

        //调用远程 接口 处理成功返回 ✔ 否则✖
        Boolean aBoolean = secretKeyBoolean(enterpriseId, JSONUtil.toJsonStr(map));
        log.info("方法返回：{}",aBoolean);
        return aBoolean;
    }

    /**
     * 省平台注册
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @return 注册结果
     */
    @Override
    public Boolean register(String enterpriseId) {
        log.info("入参：{}",enterpriseId);

        //根据主键以及未删除，查询出该条数据
        Enterprise enterprise = this.queryById(enterpriseId);
        log.info("查询出该条数据：{}",enterprise);

        //构建 省平台注册 需要的参数
        HashMap<String, String> map = getHashMap(enterprise);

        Boolean aBoolean = registerBoolean(enterpriseId, JSONUtil.toJsonStr(map));
        log.info("方法返回值：{}",aBoolean);

        return aBoolean;
    }

    /**
     * 构建 省平台注册 需要的参数
     *
     * @author : juzipi123
     * @param enterprise 社会信用代码
     * @return 注册结果
     */
    private HashMap<String, String> getHashMap(Enterprise enterprise) {
        log.info("入参：{}",enterprise);

        // 央企
        String center = "1";

        // 公共机构
        String isorg = "1";

        HashMap<String, String> map = new HashMap<>(8);
        map.put("enterpriseCode", enterprise.getEnterpriseCode());
        map.put("isorg", enterprise.getIsorg());
        map.put("password", enterprise.getPassword());
        map.put("cmpName", enterprise.getCmpName());
        map.put("address", enterprise.getAddress());

        //*邮编*/
        if (ObjectUtils.isNotEmpty(enterprise.getZipCode())) {
            map.put("zipCode", enterprise.getZipCode());
        }
        map.put("corporationName", enterprise.getCorporationName());
        map.put("regionCode", enterprise.getRegionCode());
        map.put("license", enterprise.getLicense());
        /*企业组织结构电子照片*/
        if (ObjectUtils.isNotEmpty(enterprise.getOrganization())) {
            map.put("organization", enterprise.getOrganization());
        }
        map.put("registerAddress", enterprise.getRegisterAddress());
        map.put("registerDate", enterprise.getRegisterDate());
        map.put("registerPrincipal", enterprise.getRegisterPrincipal());
        map.put("typeCode", enterprise.getTypeCode());
        map.put("industryCode", enterprise.getIndustryCode());

        map.put("fieldCode", enterprise.getFieldCode());
        map.put("energyConsumeLevel", enterprise.getEnergyConsumeLevel());
        map.put("center", enterprise.getCenter());
        map.put("jgzh", enterprise.getJgzh());
        map.put("latitude", enterprise.getLatitude());

        map.put("longitude", enterprise.getLongitude());
        map.put("phone", enterprise.getPhone());
        if (ObjectUtils.isNotEmpty(enterprise.getFax())) {
            /*传真*/
            map.put("fax", enterprise.getFax());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getEmail())) {
            /*电子邮箱（法人）*/
            map.put("email", enterprise.getEmail());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getUrl())) {
            /*用能单位网站地址*/
            map.put("url", enterprise.getUrl());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getProductionLine())) {
            /*企业主要生产线名称*/
            map.put("productionLine", enterprise.getProductionLine());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getLeadingProduct())) {
            /*企业主导产品*/
            map.put("leadingProduct", enterprise.getLeadingProduct());
        }
        if (center.equals(enterprise.getCenter())) {
            /*集团名称 （如果是央企需要填写）*/
            map.put("groupName", enterprise.getGroupName());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getGroupAddress())) {
            /*集团地址*/
            map.put("groupAddress", enterprise.getGroupAddress());
        }
        if (ObjectUtils.isNotEmpty(enterprise.getRemark())) {
            /*备注*/
            map.put("remark", enterprise.getRemark());
        }
        //如果是公共机构需要填写
        if (isorg.equals(enterprise.getIsorg())) {
            map.put("orgType", enterprise.getOrgType());
            map.put("orgCode", enterprise.getEnterpriseCode());
        }
        log.info("方法返回值：{}",map);
        return map;
    }

    /**
     * 企业信息修改
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @return 结果
     */
    @Override
    public Boolean updateByIdRegister(String enterpriseId) {
        log.info("入参：{}",enterpriseId);
        //根据主键以及未删除，查询出该条数据
        Enterprise enterprise = this.getById(enterpriseId);
        log.info("查询出该条数据：{}",enterprise);

        //构建 省平台注册 需要的参数
        HashMap<String, String> map = getHashMap(enterprise);
        map.put("dataIndex", enterprise.getDataIndex());

        Boolean aBoolean = updateByIdRegisterBoolean(enterpriseId, JSONUtil.toJsonStr(map));
        log.info("方法返回：{}",aBoolean);
        return aBoolean;
    }

    /**
     * 手动获取token
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @return token
     */
    @Override
    public String getToken(String enterpriseId) {
//        String reqUrl = host + requestAk;
        //根据主键以及未删除，查询出该条数据
        log.info("入参:{}",enterpriseId);
        Enterprise enterprise = this.getById(enterpriseId);
        log.info("查询出该条数据：{}",enterprise);

        //构建 手动获取token 需要的参数
        HashMap<String, String> map = new HashMap<>(2);
        map.put("enterpriseCode", enterprise.getEnterpriseCode());
        map.put("password", enterprise.getPassword());
        String enterpriseCode = getTokenString(JSONUtil.toJsonStr(map), map.get("enterpriseCode"));
        log.info("方法返回值：{}",enterpriseCode);
        return enterpriseCode;
    }

    /**
     * @Author zelinwang
     * @param conditionJson
     * @param pageNum 页码
     * @param pageSize 页数
     * @return
     */
    @Override
    public PageResult<Enterprise> pageList(String conditionJson, int pageNum, int pageSize) {
        Page<Enterprise> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Enterprise> queryWrapper = SearchUtil.parseWhereSql(null, null, conditionJson);
        Page<Enterprise> pageList = userRoleUtil.getPageList(page, queryWrapper, this.baseMapper);
        return new PageResult<>(pageList);
    }

    /**
     * @author : juzipi123
     * @param json 参数
     * @param enterpriseCode 社会信用代码
     * @return
     */
    private String getTokenString(String json,String enterpriseCode) {
        log.info("入参：{},{}",json,enterpriseCode);
        String reqUrl = host + requestAk;

        try {
            log.info("请求地址：{}",reqUrl);
            String result = client.getToken(reqUrl, json);
            log.info("请求地址返回值：{}",result);

            //结果转成 JSONObject
            JSONObject resultJson = JSONUtil.parseObj(result);
            log.info("resultJson ====={}", resultJson);
            Integer responseCode = (Integer) resultJson.get("responseCode");

            //返回的结果正确 200 对数据处理
            if (HttpStatus.HTTP_OK == responseCode) {
                JSONObject dataObject = resultJson.getJSONObject("data");
                TEpUploadTimeDTO uploadTimeDTO = new TEpUploadTimeDTO();
                String timeStr = dataObject.getStr("enterpriseUploadTime");
                // 格式化时间
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                String[] split = timeStr.split("-");
                Time sTime = null;
                Time eTime = null;
                try {
                    sTime = new Time(format.parse(split[0]).getTime());
                    eTime = new Time(format.parse(split[1]).getTime());
                } catch (ParseException e) {
                    log.info("日期格式化异常：{}", e.toString());
                }

                uploadTimeDTO.setEnterpriseCode(enterpriseCode);
                uploadTimeDTO.setStartTime(sTime);
                uploadTimeDTO.setEndTime(eTime);
                uploadTimeDTO.setToken(dataObject.getStr("token"));
                uploadTimeService.saveOrUpdate(uploadTimeDTO);
                return String.valueOf(dataObject);
            } else {
                throw new BusinessException(500, resultJson.get("responseMessage").toString());
            }

        } catch (Exception e) {
            log.error("调用第三方 企业信息修改 异常：{}", e);

            throw new BusinessException(500, e.getMessage());
        }
    }


    /**
     * 调用 企业信息修改 接口
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @param json         参数
     * @return 结果
     */
    private Boolean updateByIdRegisterBoolean(String enterpriseId, String json) {
        log.info("入参：{},{}",enterpriseId,json);
        String reqUrl = host + update;

        try {
            log.info("请求地址：{}",reqUrl);
            String result = client.updateByIdRegister(reqUrl, json);
            log.info("请求地址返回值：{}",result);

            JSONObject resultJson = JSONUtil.parseObj(result);
            log.info("resultJson ====={}", resultJson);
            Integer responseCode = (Integer) resultJson.get("responseCode");

            //返回的结果正确 200 对数据处理
            if (HttpStatus.HTTP_OK == responseCode) {
                Object dataObject = resultJson.get("data");
                String data = String.valueOf(dataObject);
                JSONObject dataJson = JSONUtil.parseObj(data);
                String dataIndexNew = (String) dataJson.get("dataIndex");

                //修改数据库 记录索引号 字段
                LambdaUpdateChainWrapper<Enterprise> updateChainWrapper = new LambdaUpdateChainWrapper<>(this.getBaseMapper());
                updateChainWrapper.set(Enterprise::getDataIndex, dataIndexNew);
                updateChainWrapper.eq(Enterprise::getEnterpriseId, enterpriseId);
                updateChainWrapper.eq(Enterprise::getDelFlag, 0);

                boolean update = updateChainWrapper.update();
                log.info("方法返回：{}",update);
                return update;
            } else {
                throw new BusinessException(500, resultJson.get("responseMessage").toString());
            }

        } catch (Exception e) {
            log.error("调用第三方 企业信息修改 异常：{}", e);

            throw new BusinessException(500, e.getMessage());
        }
    }

    /**
     * 调用 获取工作密钥 接口
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @param param        参数
     * @return 结果
     */
    private Boolean secretKeyBoolean(String enterpriseId, String param) {
        log.info("入参：{},{}",enterpriseId,param);
        String reqUrl = host + rwk;

        try {
            log.info("请求地址：{}",reqUrl);
            String result = client.getSecretKey(reqUrl, param);
            log.info("请求地址返回值：{}", result);

            //结果转成 JSON
            JSONObject resultJson = new JSONObject(result);

            log.info("resultJson ====={}", resultJson);
            Integer responseCode = (Integer) resultJson.get("responseCode");

            //返回的结果正确 200 对数据处理
            if (Integer.valueOf(HttpStatus.HTTP_OK).equals(responseCode)) {
                Object dataObject = resultJson.get("data");
                JSONObject dataJson = JSONUtil.parseObj(dataObject);

                String secretKeyNew = dataJson.get("secretKey").toString();

                //修改数据库 工作密钥 字段
                LambdaUpdateChainWrapper<Enterprise> updateChainWrapper = new LambdaUpdateChainWrapper<>(this.getBaseMapper());
                updateChainWrapper.set(Enterprise::getSecretKey, secretKeyNew);
                updateChainWrapper.eq(Enterprise::getEnterpriseId, enterpriseId);
                updateChainWrapper.eq(Enterprise::getDelFlag, 0);
                boolean update = updateChainWrapper.update();
                log.info("方法返回：{}",update);
                return update;
            } else {
                throw new BusinessException(500, resultJson.get("responseMessage").toString());
            }
        } catch (Exception e) {
            log.error("调用第三方接口获取工作密钥异常：{}", e);

            throw new BusinessException(500, e.getMessage());
        }
    }

    /**
     * 调用 端系统注册申请 接口
     *
     * @author : juzipi123
     * @param enterpriseId 社会信用代码
     * @param json         参数
     * @return 结果
     */
    private Boolean registerBoolean(String enterpriseId, String json) {
        log.info("入参：{},{}",enterpriseId,json);

        String reqUrl = host + apply;

        try {
            log.info("请求地址：{}",reqUrl);
            String result = client.register(reqUrl, json);
            log.info("请求地址返回值：{}",result);

            JSONObject resultJson = JSONUtil.parseObj(result);
            log.info("resultJson ====={}", resultJson);
            Integer responseCode = (Integer) resultJson.get("responseCode");

            //返回的结果正确 200 对数据处理
            if (HttpStatus.HTTP_OK == responseCode) {
                Object dataObject = resultJson.get("data");
                String data = String.valueOf(dataObject);
                JSONObject dataJson = JSONUtil.parseObj(data);
                String dataIndexNew = (String) dataJson.get("dataIndex");

                //修改数据库 记录索引号 字段
                LambdaUpdateChainWrapper<Enterprise> updateChainWrapper = new LambdaUpdateChainWrapper<>(this.getBaseMapper());
                updateChainWrapper.set(Enterprise::getDataIndex, dataIndexNew);
                updateChainWrapper.eq(Enterprise::getEnterpriseId, enterpriseId);
                updateChainWrapper.eq(Enterprise::getDelFlag, 0);

                boolean update = updateChainWrapper.update();
                log.info("方法返回：{}",update);
                return update;
            } else {
                throw new BusinessException(500, resultJson.get("responseMessage").toString());
            }

        } catch (Exception e) {
            log.error("调用第三方接口注册异常：{}", e);

            throw new BusinessException(500, e.getMessage());
        }
    }

    /**
     * 查询企业名称byId
     *
     * @Author YY
     * @param id 社会统一信用代码
     * @return enterprise实体
     */
    @Override
    public EnterpriseGetNameVO getEnterpriseName(String id) {
        EnterpriseGetNameVO enterprise = enterpriseMapper.getEnterpriseName(id);
        log.info("方法返回：{}",enterprise);
        return enterprise;
    }

    /**
     * 查询企业名称列表
     *
     * @Author YY
     * @return list
     */
    @Override
    public List<EnterpriseGetNameVO> getNameList() {
        //判断当前登录用户角色
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name",userName));
        //存放社会信用代码的集合
        List<String> enterpriseCodes=new ArrayList<>();
        if (user.getRoleId().equals("3")){
            List<EnterpriseGetNameVO> nameList = enterpriseMapper.getNameList();
            return nameList;
        }else{
            if (user.getRoleId().equals("1")){
                //普通用户只能看自己的
                enterpriseCodes.add(userName);
            }else if (user.getRoleId().equals("4")){
                //roleId=4 企业管理员 显示名下所有企业相关信息；
                //根据up_id查找该企业管理员下所有的普通用户user_name(企业社会信用代码)
                List<User> list=userMapper.getList(user.getId());
                enterpriseCodes = list.stream()
                        .map(User::getUserName)
                        .collect(Collectors.toList());
            }
            List<EnterpriseGetNameVO> nameList = enterpriseMapper.getNameList();
            List<String> finalEnterpriseCodes = enterpriseCodes;
            List<EnterpriseGetNameVO> matchedList = nameList.stream()
                    .filter(vo -> finalEnterpriseCodes.contains(vo.getEnterpriseCode()))
                    .collect(Collectors.toList());
            return matchedList;
        }

    }

    /**
     * 企业列表分页查询
     *
     * @author : zelinwang
     * @param conditionJson 条件器
     * @param pageNum 页码
     * @param pageSize 页数
     * @return
     */
    @Override
    public PageResult<Enterprise> enterNamePageList(String conditionJson, int pageNum, int pageSize) {
        log.info("入参：{},{},{}",conditionJson,pageNum,pageSize);
        Page<Enterprise> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Enterprise> queryWrapper = SearchUtil.parseWhereSql(null, null, conditionJson);
        Page<Enterprise> pageList = userRoleUtil.getPageList(page, queryWrapper, this.baseMapper);
        PageResult<Enterprise> enterprisePageResult = new PageResult<>(pageList);
        log.info("方法返回：{}",enterprisePageResult);
        return enterprisePageResult;
    }

    @Override
    public Boolean upDateEnterpriseInfo(String enterpriseCode) {
        String token = tokenService.getLaoGouWebToken();
        token = "ssid="+token;
        com.alibaba.fastjson.JSONObject jsonObject = ynBk.getProjectData(token,enterpriseCode).getJSONArray("rows").getJSONObject(1);
//        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("enterprise_code",enterpriseCode);
        LambdaQueryWrapper<Enterprise> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Enterprise::getEnterpriseCode,enterpriseCode);
        List<Enterprise> enterprise = this.baseMapper.selectList(queryWrapper);
        Enterprise updateData = new Enterprise();
        setEnterpriseEntity(updateData,jsonObject);
        if(enterprise.size()>0){
            //证明有企业,进行更新
            updateData.setEnterpriseId(enterprise.get(1).getEnterpriseId());
            this.baseMapper.updateById(updateData);
            return true;
        }
        //没有则进行新增
        this.baseMapper.insert(updateData);
        return true;
        //jsonObject.toJavaObject(Enterprise.class);

    }

    /**
     * 上传营业照片
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public String upLoadPicture(MultipartFile picture, HttpServletRequest request) {
        // 指定本地存储路径
        String localPath = "D:/uploads"; // 替换为实际的本地目录路径
        File localDirectory = new File(localPath);
        if (!localDirectory.exists() && !localDirectory.isDirectory()) {
            boolean isCreated = localDirectory.mkdirs(); // 创建所有缺失的父目录
            if (!isCreated) {
                return "目录创建失败";
            }
        }

        //获取原始文件名称(包含格式)
        String originalFileName = picture.getOriginalFilename();
        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称： 当前时间+文件名称（不包含格式）
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = date + name + "." + type;

        // 保存文件到本地目录
        try {
            File localFile = new File(localDirectory, fileName);
            picture.transferTo(localFile);
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }

//        //将文件保存到远程服务器指定位置
//        CloseableHttpClient httpClient=null;
//        CloseableHttpResponse response=null;
//        try {
//            httpClient = HttpClients.createDefault();
//            //指定远程服务器地址
//            HttpPost httpPost = new HttpPost("https://localhost/upload"); // 替换为实际的服务器地址
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//            builder.addBinaryBody("file", picture.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//            HttpEntity multipart = builder.build();
//            httpPost.setEntity(multipart);
//            response = httpClient.execute(httpPost);
//            int statusCode = response.getStatusLine().getStatusCode();
//            if (statusCode == 200) {
//                return Res.ok("/upload/" + fileName);
//            } else {
//                return Res.ok("上传失败");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Res.ok("上传失败");
//        }finally {
//            try {
//                httpClient.close();
//                response.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    public void setEnterpriseEntity(Enterprise updateData, com.alibaba.fastjson.JSONObject jsonObject){
        updateData.setRegionCode(jsonObject.get("areaCode").toString());//区划代码
        updateData.setCenter(jsonObject.get("centrEnt").toString());//是否央企
        updateData.setAddress(jsonObject.get("coAddr").toString());//公司地址
        updateData.setOrganization(jsonObject.get("coLicen").toString());//营业执照base64
        updateData.setCmpName(jsonObject.get("coName").toString());//企业名称
        updateData.setCorporationName(jsonObject.get("coName").toString());//法人代表
        updateData.setTypeCode(jsonObject.get("coType").toString());//公司类型
        updateData.setUrl(jsonObject.get("coWeb").toString());//公司网站
        updateData.setFieldCode(jsonObject.get("domCode").toString());//领域编码
        updateData.setEnergyConsumeLevel(jsonObject.get("eneLevel").toString());//企业能耗级别
        updateData.setJgzh(jsonObject.get("energyProces").toString());//能源加工转换种类企业
        updateData.setFax(jsonObject.get("fax").toString());//传真
        updateData.setGroupAddress(jsonObject.get("groupAddr").toString());//集团地址
        updateData.setGroupName(jsonObject.get("groupName").toString());//集团名称
        updateData.setIndustryCode(jsonObject.get("indCode").toString());//行业编码
        updateData.setLongitude(jsonObject.get("latitude").toString());//主要厂址中心纬度
        updateData.setLatitude(jsonObject.get("longitude").toString());//主要厂址中心经度
        updateData.setProductionLine(jsonObject.get("plineName").toString());//主要生产线名称
        updateData.setZipCode(jsonObject.get("posCode").toString());//邮政编码
        updateData.setLeadingProduct(jsonObject.get("products").toString());//主导产品
        updateData.setIsorg(jsonObject.get("pubIns").toString());//是否公共机构
        updateData.setRegisterAddress(jsonObject.get("regAddr").toString());//公司注册地址
        updateData.setRegisterPrincipal(jsonObject.get("regCapital").toString());//注册资金(万元)
        updateData.setRegisterDate(jsonObject.get("regDt").toString());//公司注册日期
        updateData.setEmail(jsonObject.get("reprEmail").toString());//法人电子邮箱
        updateData.setPhone(jsonObject.get("reprPhone").toString());//	法人电话
        updateData.setEnterpriseCode(jsonObject.get("uscCode").toString());//统一社会信用代码
    }

}